package com.jee.project.controller;

import com.jee.project.model.Course;
import com.jee.project.repo.CourseRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/course")
@Tag(name = "course module", description = "课程管理模块")
public class CourseController {

    @Autowired
    private CourseRepository courseRepo;


    @GetMapping("/course")
    public Iterable<Course> getAllCourses() {
        return courseRepo.findAll();
    }


    @GetMapping("/course/{id}")
    public Course getCourseById(@PathVariable("id") Course course) {
        return course;
    }


    @PostMapping("/course")
    @Operation(summary = "创建课程")
    public Course addCourse(@Valid @RequestBody Course course) {
        return courseRepo.save(course);
    }


    @PutMapping("/course/{id}")
    public Course editCourse(@PathVariable("id") Course course, @RequestParam("code") String code, @RequestParam("name") String name) {
        course.setCode(code);
        course.setName(name);
        courseRepo.save(course);
        return course;
    }


    @DeleteMapping("/course/{id}")
    public String delCourse(@Parameter(example = "1") @PathVariable("id") Long id) {
        try {
            courseRepo.deleteById(id);
            return "删除成功！";
        } catch (Exception ex) {
            return "删除失败";
        }
    }

    /**
     * 拦截本类中的验证异常， 把错误信息整理成易于前端处理的格式。
     *
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, Object> handleValidationExceptions(MethodArgumentNotValidException ex) {

        List errors = new ArrayList<String>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            errors.add(error.getDefaultMessage());
        });

        // 拼接结果
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("failure", true);  // 用于判断是否失败
        result.put("message", errors);
        return result;
    }
}
